<template>
  <div class="yxp-course">
    <TopBack :title="title" type="2" :id="id" :courseId="courseId" :course_type="course_type" @point="handlePoint"/>
    <div class="yxp-scene-main">
      <div class="main-box">
        <div class="main-box-item">
          <div class="buffer" v-if="isBuffer">
            <div class="buffer-item">
              <!-- <span v-for="(item,i) in buffer" :Key="'b' + i" :style="{height: Math.abs(item / 20) + 'px'}"></span> -->
              <div class="buffer-item-l">
                <span v-show="voice >= 1" ></span>
                <span v-show="voice >= 2"></span>
                <span v-show="voice >= 3"></span>
                <span v-show="voice >= 4"></span>
                <span v-show="voice >= 5"></span>
                <span v-show="voice >= 6"></span>
                <span v-show="voice >= 7"></span>
                <span v-show="voice >= 8"></span>
                <span v-show="voice >= 9"></span>
                <span v-show="voice >= 10"></span>
              </div>
              <div class="buffer-item-r">
                <span v-show="voice >= 1" ></span>
                <span v-show="voice >= 2"></span>
                <span v-show="voice >= 3"></span>
                <span v-show="voice >= 4"></span>
                <span v-show="voice >= 5"></span>
                <span v-show="voice >= 6"></span>
                <span v-show="voice >= 7"></span>
                <span v-show="voice >= 8"></span>
                <span v-show="voice >= 9"></span>
                <span v-show="voice >= 10"></span>
              </div>
            </div>
            <!-- <div class="buffer-item bg-item">
                <span v-for="(item,i) in buffer" :Key="'b1' + i"></span>
              </div> -->
            <div class="buffer-btn" id="yxp-trans-stop" @click="realTimeAsrStop">完成录音</div>
          </div>
          <div class="content">
            <div class="content-wrap translates-box">
              <p class="info">
              <template>
                <template v-if="articleType === 1 || articleType === 5">
                  <span v-html="zhHead"  :style="{display: 'block',color: '#333'}"></span>
                  <span v-for="(item,i) in zhText" :key="'z' + i"  v-html="item"></span>
                  <span v-html="zhEnd" :style="{float: 'right',overflow: 'hidden'}"></span>
                </template>
                <template v-else-if="articleType === 2">
                  <span v-html="zhHead"  :style="{display: 'block','text-align': 'center',color: '#333'}"></span>
                  <span v-for="(item,i) in zhText" :key="'z' + i"  v-html="item"></span>
                  <span v-html="zhEnd" :style="{float: 'right',overflow: 'hidden'}"></span>
                </template>
                <template v-else-if="articleType === 3">
                  <span v-html="zhHead"  :style="{display: 'block','text-align': 'center',color: '#333'}"></span>
                  <span v-for="(item,i) in zhText" :key="'z' + i"  v-html="item"></span>
                </template>
                <template v-else-if="articleType === 4">
                  <span v-html="zhHead" :style="{display: 'block',color: '#333'}"></span>
                  <span v-for="(item,i) in zhText" :key="'z' + i"  v-html="item"></span>
                </template>
                <template v-else>
                  <span v-for="(item,i) in zhText" :key="'z' + i"  v-html="item"></span>
                </template>
              </template>
            </p>
            </div>
          </div>
          <div class="record" :style="{height: isRad ? '170px' : '120px'}">
          <div class="record-similary" v-if="isComplete">匹配度：{{rad}}%</div>
          <div class="record-box">
            <div class="record-box-item" v-if="!playing" id="yxp-trans-play1" @click="playVoice('play')">
              <img src="@/assets/composition/record-play.png" />
              <p class="record-box-item-text">播放读音</p>
            </div>
            <div class="record-box-item" v-if="playing" id="yxp-trans-play2" @click="playVoice('pause')">
              <img src="@/assets/composition/pause-icon.png" />
              <p class="record-box-item-text">结束播放</p>
            </div>
            <div class="record-box-item" id="yxp-trans-open"  @click="realTimeAsrOpen">
              <img src="@/assets/composition/record-icon.png" />
              <p class="record-box-item-text">朗读全文</p>
            </div>
          </div>
        </div>
        </div>
      </div>
    </div>
    <div class="scene">
      <div class="scene-btn" :style="{justifyContent: playing ? 'space-between' : 'center'}">
        <div class="scene-btn-item" v-if="playing">
          <!-- v-if="playing" -->
          <span class="ms">{{ seekDuration | mmssFilter }}</span>
          <a-slider class="voice-range" :value="sliderPercentage"></a-slider>
          <span class="ms">{{ audioDuration | mmssFilter }}</span>
        </div>
        <div class="scene-btn-item" id="yxp-trans-scene" @click="handleScene">
          <span class="model">模型训练</span>
          <img src="@/assets/word/no-next.png" />
        </div>
      </div>
    </div>
    <div class="mark" v-if="isPoint || isEn"></div>
    <readPop :isPoint="isPoint" :content="content.analysis" @point="handlePoint" />
    <!--英文训练弹窗-->
    <ScenePop :title="popTitle" :isEn="isEn" type="1" :id="id" :courseType="course_type" :courseId="courseId" @closePop="handleClosePop" />
    <!-- <div class="buffer-wrap" v-if="isBuffer">
    <div class="buffer" v-if="isBuffer">
      <div class="buffer-item">
        <div class="buffer-item-l">
          <span v-if="voice >= 1" ></span>
          <span v-if="voice >= 2"></span>
          <span v-if="voice >= 3"></span>
          <span v-if="voice >= 4"></span>
          <span v-if="voice >= 5"></span>
          <span v-if="voice >= 6"></span>
          <span v-if="voice >= 7"></span>
          <span v-if="voice >= 8"></span>
          <span v-if="voice >= 9"></span>
          <span v-if="voice >= 10"></span>
        </div>
        <div class="buffer-item-r">
          <span v-if="voice >= 1" ></span>
          <span v-if="voice >= 2"></span>
          <span v-if="voice >= 3"></span>
          <span v-if="voice >= 4"></span>
          <span v-if="voice >= 5"></span>
          <span v-if="voice >= 6"></span>
          <span v-if="voice >= 7"></span>
          <span v-if="voice >= 8"></span>
          <span v-if="voice >= 9"></span>
          <span v-if="voice >= 10"></span>
        </div>
      </div>
      <div class="buffer-btn" @click="realTimeAsrStop">完成录音</div>
    </div>
    </div> -->
  </div>
</template>
<script>
import Recorder from 'recorder-core'
import 'recorder-core/src/engine/mp3'
import 'recorder-core/src/engine/mp3-engine'
import { Slider } from "ant-design-vue"
import TopBack from '../components/TopBack.vue'
import ScenePop from '../components/ScenePop.vue'
import readPop from '../components/readPop.vue'
import storage from '@/utils/storage.js'
import { zhSimilarity2Percent } from '@/utils/rand.js'
import { Howl } from "howler"
export default {
  name: 'sceneIndex',
  components: {
    TopBack,
    ScenePop,
    readPop,
    ASlider: Slider
  },
  data () {
    return {
      asrData: [],
      recIsOpen: false,
      BSync: null,
      isController: false,
      title: '情景植入',
      popTitle: '开始英语表达训练吧~',
      content: '',
      zhText: [],
      zhHead: '',
      zhEnd:'',
      zhWord: '',
      courseId: '',
      id: 0,
      course_type: 0,
      isPoint: false,
      isBuffer: false,
      isComplete: false,
      isEn: false,
      currentTime: 0,
      durationTime: 0,
      isPlay: false,
      hideLoading: false,
      move: {
        startX: 0,
        left: 0
      },
      w: 0,
      DB: 0,
      socket: null,
      rec: null,
      wave: null,
      recBlob: null,
      recordTransformData: null,
      recordStarted: false,
      voiceResult: '',
      voiceModel: '',
      voice: 15,
      max_record: 0,
      min_record: 0,
      bufferDuration: 0,
      rad: 0,
      playing: false,
      project_voice: '',
      audioDuration: 0,
      seekDuration: 0,
      result: '',
      resultVoice: '',
      articleType: 1,
      isStop: false,
      isAllow: false,
      isRad: false,
      buffer: [],
      sn: window.location.href
    }
  },
  computed: {
    sliderPercentage: function() {
      return this.seekDuration < 1 ? 0 : Math.ceil((this.seekDuration / this.audioDuration) * 93)+7;
    }
  },
  watch: {
    DB (newDb) {
      console.log(newDb, 'new DB')
      if (+newDb === 0) {
        this.voice = 0;
      } else if (newDb >= 1 && newDb <= 20) {
        // 显示一格音谱
        this.voice = 1;
      } else if (newDb >= 21 && newDb <= 40) {
        this.voice = 2;
        // 显示二格音谱
      } else if (newDb >= 41 && newDb <= 60) {
        this.voice = 3;
        // 显示三格音谱
      } else if (newDb >= 71 && newDb <= 90) {
        this.c = 4;
        // 显示四格音谱
      } else if (newDb >= 91 && newDb <= 120) {
        this.voice = 5;
        // 显示五格音谱
      } else if (newDb >= 121 && newDb <= 140) {
        this.voice = 6;
        // 显示六格音谱
      } else if (newDb >= 141 && newDb <= 160) {
        this.voice = 7;
        // 显示七格音谱
      } else if (newDb >= 161 && newDb <= 180) {
        this.voice = 8;
        // 显示八格音谱
      } else if (newDb >= 181 && newDb <= 200) {
        this.voice = 9;
        // 显示九格音谱
      } else if (newDb > 200) {
        this.voice = 10;
        // 显示全部音谱
      }
    }
  },
  created () {
    this.BSync = window.isBSync()
    this.isController = window.isController()
    this.realTimeAsrInit()
    console.log(typeof this.popTitle)
    let { courseId, id, course_type } = this.$route.query
    console.log(id + '*****')
    this.courseId = +courseId
    this.id = +id
    this.course_type = +course_type
    let data = storage.get('sceneData')
    let audiosrc = data.ch_voice
    this.project_voice = audiosrc
    if (data) {
      this.content = data
      this.articleType = data.type
      this.max_record = data.max_record
      this.min_record = data.min_record
      let zhText = data.sentence_translation
      let zhArr = []
      let zhArr1 = []
      if (this.articleType === 1 || this.articleType === 5 || this.articleType === 2) {
        this.zhHead = zhText.splice(0,1).join('').replace('##','')
        this.zhEnd = zhText.pop()
      } else if (this.articleType === 3 || this.articleType === 4) {
        console.log(zhText)
        this.zhHead = zhText.splice(0,1).join('').replace('##','')
      }
      zhText.map(item =>{
        if (item.indexOf('&&') !== -1 || item.indexOf('##') !== -1) {
          let val = item.replace('&&', '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;').replace('##','<br>')
          let val1 = item.replace('&&', '').replace('##', '')
          zhArr.push(val)
          zhArr1.push(val1)
        } else {
          zhArr.push(item)
          zhArr1.push(item)
        }
      })
      this.zhText = zhArr
      this.zhWord = zhArr1.join('')
    }
  },
  mounted() {
    let vm = this;
    this.audio = new Howl({
      src: this.project_voice,
      html5: true,
      onplay: function() {
        vm.playing = true;
        vm.seekTimer = setInterval(() => {
          vm.audioDuration = this.duration();
          vm.seekDuration = this.seek();
        }, 1000);
      },
      onload: function() {
        vm.audioDuration = this.duration();
      },
      onpause: function() {
        vm.playing = false;
      },
      onend: function() {
        console.log("end");
        vm.playing = false;
        vm.seekDuration = this.duration();
        clearInterval(vm.seekTimer)
      }
    });
  },
  beforeDestroy () {
    if (this.audio) {
      this.audio.stop()
    }
    clearInterval(this.seekTimer)
    this.isStop = false
    if (this.rec !== null) {
      this.realTimeAsrStop()
      this.rec = null
    }
    // this.socket.removeEventListener('open',true)
    // this.socket.removeEventListener('message',true)
    // this.socket.removeEventListener('close',true)

  },
  methods: {
    realTimeAsrInit () {
      let that = this
      !this.rec && (this.rec = Recorder({
        type: 'mp3',
        sampleRate: 16000,
        bitRate: 16,
        bufferSize: 4096,
        onProcess: (buffers, powerLevel, bufferDuration, bufferSampleRate) => {
          this.recordTransformData = Recorder.SampleData(buffers, bufferSampleRate, 16000, {
            index: this.recordTransformData ? this.recordTransformData.index: 0,
            offset: this.recordTransformData ? this.recordTransformData.offset: 0.0,
          });
          // 业务处理-start
          let buffer = buffers[buffers.length-1]
          this.buffer = buffer
          var maxVal = 0;
          for (var i = 0; i < buffer.length; i++) {
              if (maxVal < buffer[i]) {
                  maxVal = buffer[i];
              }
          }
          this.DB = parseInt(maxVal / 100);
          // 业务处理-end
          if (bufferDuration / 1000 > this.min_record) {
            this.isStop = false
          }
          this.socket.send(this.recordTransformData.data)
          if (bufferDuration / 1000 >= this.max_record) {
            this.asrSyncStopEvent()
          }
        }
      }))
      if(!that.isController){
        that.BSync && that.BSync.socket.on('sync:socket', function (data) {
          that.realTimeAsrMessage(data)
        })
        that.BSync && that.BSync.socket.on('sync:cmd', function (data) {
          console.log('==================', data, that.sn, '=========')
          if (data.sn === that.sn) {
            data.cmd && eval(`typeof ${data.cmd} == 'function' && ${data.cmd}(data)`)
          }
        })
      }
      this.realTimeAsrOpen(false)
    },
    _realTimeAsrOpen () {
      console.log('正在启动转写')
      let that = this
      this.socket = new WebSocket(`wss://vop.baidu.com/realtime_asr?sn=${new Date().getTime()}`, 'websocket')
      this.socket.addEventListener('open', () => {
        this.socket.send(JSON.stringify({
          "type": "START",
          "data": {
            "appid": 38946723,
            "appkey": "SpFCiGxeEeTBYY86mGB24s4E",
            "dev_pid": 15372,
            "cuid": "cuid-1",
            "format": "pcm",
            "sample": 16000
          }
        }))
        this.DB = 0
        this.isBuffer = true
        this.isVoice = false
        this.isModel = false
        this.isStop = true
        this.voiceResult = ''
        this.voiceModel = ''
        this.rec.start()
      })
      if(that.isController){
        this.socket.addEventListener('message', (msgevt) => {
          let data = msgevt.data
          if(data){
            data = JSON.parse(data)
            if(data.err_no == 0){
              that.BSync && that.BSync.socket.emit('sync:socket', data)
              that.realTimeAsrMessage(data)
            }
          }
        })
      }
      this.socket.addEventListener('close', (e) => {
        console.log('关闭连接', e)
        if (e.target.url === this.socket.url) {
          this.asrSyncStopEvent()
        }
      })
    },
    _realTimeAsrMessage (data) {// 业务处理
      console.log('业务处理.识别数据', data)
      this.voiceModel = data.join(' ')
      this.voiceResult = data.join(' ')
    },
    realTimeAsrMessage (data) {
      console.log('原始数据', data)
      this.asrData[this.asrData.length == 0 ? 0 : (this.asrData.length - 1)] = data.result
      if(data.type == 'FIN_TEXT'){
        this.asrData[this.asrData.length] = ''
      }
      this._realTimeAsrMessage(this.asrData)
    },
    asrSyncStopEvent () {
      let that = this
      // 传递关闭事件
      if(that.isController){
        that.BSync && that.BSync.socket.emit('sync:cmd', {
          cmd: 'that.realTimeAsrStop',
          sn: that.sn
        })
        that.realTimeAsrStop()
      }
    },
    realTimeAsrStop () {
      // 加锁
      if (this.bufferDuration / 1000 < this.min_record && this.isStop) {
        this.$message.error('录音时间太短哦~')
        return
      }
      if(this.recordTransformData){
        this.recordTransformData = null
        this.asrData = []
        this.isBuffer = false
        this.isVoice = true
        this.isModel = true
        this.voiceResult = ''
        // console.log(this.voiceModel)
        // console.log(this.zhWord)
        let reg = /[~。，\s！!?<>@#$%^&*()+=:“”.,"]/g
        let v = this.voiceModel.replace(reg, '')
        let t = this.zhWord.replace(reg, '')
        console.log(v)
        console.log(t)
        let rad = zhSimilarity2Percent(v, t) * 100
        this.rad = rad.toFixed(2)
        this.isRad = true
        this.isComplete = true
        this.isStop = false
        this.rec.stop((blob, duration) => {
          console.log(33, blob, duration)
        })
      }
    },
    realTimeAsrOpen (asr = true) {
      if (this.isAllow) {
        this.$message.error('请先打开麦克风')
        return
      }
      if (this.playing) {
        this.$message.error('请先暂停播放读音')
        return
      }
      // 加锁
      if(this.recordTransformData) return false
      console.log('正在打开录音组件')
      if(this.recIsOpen){
        if(asr) return this._realTimeAsrOpen()
        else return false
      }
      this.rec.open(success => {
        console.log('rec.open', success)
        this.recIsOpen = true
        if(this.recIsOpen){
          if(asr) return this._realTimeAsrOpen()
          else return false
        }
      }, (msg, isUserNotAllow) => {//用户拒绝未授权或不支持
          this.isAllow = isUserNotAllow
          console.log(msg + '&' + isUserNotAllow)
          this.$message.error("请先打开麦克风");
      })
    },
    handleCloaseModel () {
      this.isModel = false
    },
    handleScene () {
      if (this.isBuffer) return
      this.isEn = true
    },
    handlePoint (val) {
      this.isPoint = val
    },
    handleClosePop (val) {
      this.isEn = val
    },
    playVoice (status) {
      if (status === 'play') {
        this.playing = true
        this.audio.play()
      } else {
        this.playing = false
        this.audio.pause()
      }
    },
    loadError (e) {
      console.log(e)
    }
  }
}
</script>
<style lang="less" scoped>
.translates-box {
  height: calc(100% - 150px) !important;
  overflow: auto !important;
  padding-top: 42px !important;
}
.info {
        font-size: 20px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #333;
      }
.record {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      .record-similary {
        font-size:20px;
        font-family:Microsoft YaHei;
        font-weight:400;
        color: #27BFA3;
        padding-top: 24px;
      }
      &-box {
        position: absolute;
        left:0;
        bottom: 20px;
        display: flex;
        justify-content: center;
        width: 100%;
        text-align: center;
        background: #fff;
        opacity: .95;
        &-item {
        &:first-child {
          cursor: pointer;
          margin-right: 90px;
        }
        img {
          width: 80px;
          height: 80px;
        }
        &-text {
          font-size: 16px;
          font-family: Microsoft YaHei;
          font-weight: 400;
          color: #27BFA3;
          margin-top: -13px;
        }
      }
      }

    }


  .yxp-scene-audio {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    width: 600px;
    height: 400px;
    background: #fff;
    border-radius: 10px;
    .close {
      position: absolute;
      right: 20px;
      top: 20px;
      width: 20px;
      height: 20px;
      cursor: pointer;
    }
    .btn {
      width: 269px;
      height: 60px;
      line-height: 60px;
      text-align: center;
      font-size: 24px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #fff;
      background: #3BC9A4;
      border-radius: 100px;
      margin: 290px auto 0;
      cursor: pointer;
    }
  }
.buffer-wrap {
  position: fixed;
  left: 50%;
  transform: translateX(-50%);
  bottom: 20px;
  width: 800px;
  height: 190px;
  z-index: 19;
}
.buffer {
    position: absolute;
    left: 50%;
    bottom: -60px;
    transform: translateX(-50%);
    width: 340px;
    height: 190px;
    background: #E7F2EF;
    border-radius: 10px;
    z-index: 20;
    .bg-item {
      z-index: 2;
      span {
        background: #eee;
      }
    }
    .sec-item {
      z-index: 3
    }
    &-item {
      position: absolute;
      left: 50%;
      bottom: 65px;
      transform: translateX(-50%);
      display: flex;
      justify-content: center;
      align-items: flex-end;
      margin-bottom: 20px;
      margin-top: 20px;
      span {
        display: inline-block;
        width: 2px;
        height: 40px;
        background: #47CBB3;
        border-radius: 3px;
        margin-right: 3px;
        &:nth-child(1) {
          height: 20px;
        }
        &:nth-child(2) {
          height: 24px;
        }
        &:nth-child(3) {
          height: 28px;
        }
        &:nth-child(4) {
          height: 32px;
        }
        &:nth-child(5) {
          height: 36px;
        }
        &:nth-child(6) {
          height: 36px;
        }
        &:nth-child(7) {
          height: 32px;
        }
        &:nth-child(8) {
          height: 28px;
        }
        &:nth-child(9) {
          height: 24px;
        }
        &:nth-child(10) {
          height: 20px;
        }
      }
    }
    &-btn {
      position: fixed;
      left: 50%;
      bottom: 20px;
      transform: translateX(-50%);
      width: 200px;
      height: 46px;
      line-height: 46px;
      text-align: center;
      font-size:20px;
      font-family:Microsoft YaHei;
      font-weight:400;
      color: #fff;
      background:linear-gradient(360deg,rgba(71,203,179,1) 0%,rgba(81,211,176,1) 100%);
      box-shadow:0px 5px 10px rgba(59,201,164,0.3);
      border-radius: 100px;
    }
  }
// .yxp-recorder-pop {
//   position: fixed;
//   left: 50%;
//   top: 50%;
//   transform: translate(-50%,-50%);
//   width: 600px;
//   height: 400px;
//   background: #fff;
//   border-radius: 10px;
//   z-index: 1200;
//   .close {
//     position: absolute;
//     right: 20px;
//     top: 20px;
//     width: 20px;
//     height: 20px;
//     cursor: pointer;
//   }
//   .recorder-list {
//     display: flex;
//     justify-content: center;
//     align-items: center;
//     margin-top: 90px;
//     margin-bottom: 90px;
//     &-item {
//       display: flex;
//       justify-content: center;
//       align-items: center;
//       margin-bottom: 20px;
//       margin-top: 20px;
//       span {
//         display: inline-block;
//         width: 2px;
//         background: #47CBB3;
//         border-radius: 1px;
//         margin-right: 5px;
//         &:nth-child(1) {
//           height: 20px;
//         }
//         &:nth-child(2) {
//           height: 24px;
//         }
//         &:nth-child(3) {
//           height: 28px;
//         }
//         &:nth-child(4) {
//           height: 32px;
//         }
//         &:nth-child(5) {
//           height: 36px;
//         }
//         &:nth-child(6) {
//           height: 36px;
//         }
//         &:nth-child(7) {
//           height: 32px;
//         }
//         &:nth-child(8) {
//           height: 28px;
//         }
//         &:nth-child(9) {
//           height: 24px;
//         }
//         &:nth-child(10) {
//           height: 20px;
//         }
//       }
//     }

//   }
//   .btn {
//     position: absolute;
//     left: 50%;
//     bottom: 50px;
//     transform: translateX(-50%);
//     width: 269px;
//     height: 60px;
//     line-height: 60px;
//     text-align: center;
//     font-size:24px;
//     font-family:Microsoft YaHei;
//     font-weight:400;
//     color: #fff;
//     background:linear-gradient(360deg,rgba(71,203,179,1) 0%,rgba(81,211,176,1) 100%);
//     box-shadow:0px 5px 10px rgba(59,201,164,0.3);
//     border-radius: 30px;
//   }
// }
</style>